import React, { useEffect, useState, useImperativeHandle } from 'react'
import useForm from "rc-form-hooks"
import { connect } from 'dva'
import moment from 'moment'
import { Form, Input, DatePicker, Button, Select } from 'antd'
import './index.styl'

const { Option } = Select

function HeaderSearch({ dispatch, cRef, current, searchBtn, status, today, deviceCheck: { planOptions } }) {
    const { getFieldDecorator, validateFields, resetFields, setFieldsValue, getFieldsValue } = useForm()
    useImperativeHandle(cRef, () => ({
        getFieldsValue,
        resetFields
    }));

    useEffect(() => {
        // 获取计划状态选项
        dispatch({
            type: 'deviceCheck/getPlanOption'
        })
        if (status !== '') {
            resetFields()
            setFieldsValue({
                'status': Number(status)
            })
        }
        if (status !== '' && today !== '') {
            resetFields()
            setFieldsValue({
                'endTime': moment(Date.now()),      // 最近任务任务执行结束时间
                'startTime': moment(Date.now()),    // 最近任务任务执行开始时间
                'status': Number(status), // 计划状态
            })
        }
    }, [dispatch, setFieldsValue, status, today, resetFields])

    // 提交查询
    const handleSubmit = (e) => {
        e.preventDefault()
        validateFields()
            .then((values) => {
                searchBtn({
                    ...values,
                    startTime: values['startTime'] && values['startTime'].format('YYYY-MM-DD'),
                    endTime: values['endTime'] && values['endTime'].format('YYYY-MM-DD'),
                    current,
                    size: '10',
                })
            })
            .catch(e => console.error(e.message))
    }

    // 开始时间
    const [startTime, setStartTime] = useState()
    // 结束时间
    const [endTime, setEndTime] = useState()

    // 重置
    const onReset = () => {
        setStartTime()
        setEndTime()
        resetFields()
        dispatch({
            type: 'deviceCheck/updateSerachParams',
            payload: {
                serachParams: {
                    current: 1
                }
            }
        });
    }

    // 开始时间
    const selectStartTime = (time, str) => {
        setStartTime(time)
    }

    // 开始时间
    const selectEndTime = (time, str) => {
        setEndTime(time)
    }

    // 设置开始不能选择的时间
    const disabledStartDate = startTime => {
        if (!startTime || !endTime) {
            return false
        }
        return startTime.valueOf() > endTime.valueOf()
    }

    //设置结束不能选择的时间
    const disabledEndDate = endTime => {
        if (!endTime || !startTime) {
            return false
        }
        return endTime.valueOf() <= startTime.valueOf()
    }

    return (
        <div className="deviceCheck_headerSearch">
            <Form name="nest-messages" className="self-form" onSubmit={handleSubmit}>
                <div className="flex flex1">
                    <Form.Item label="计划名称" colon={false}>
                        {getFieldDecorator('name', {
                            rules: [{ required: false, message: '请选择任务类型' }],
                        })(
                            <Input className="self-input" placeholder="请输入" />
                        )}
                    </Form.Item>
                    <Form.Item label="设备名称" colon={false}>
                        {getFieldDecorator('deviceName', {
                            rules: [{ required: false, message: '请选择任务类型' }],
                        })(
                            <Input className="self-input" placeholder="请输入" />
                        )}
                    </Form.Item>
                    <Form.Item label="设备使用部门" colon={false}>
                        {getFieldDecorator('groupName', {
                            rules: [{ required: false, message: '请选择任务类型' }],
                        })(
                            <Input className="self-input" placeholder="请输入" />
                        )}
                    </Form.Item>
                    <Form.Item label="点检员" colon={false}>
                        {getFieldDecorator('checkUser', {
                            rules: [{ required: false, message: '请选择任务类型' }],
                        })(
                            <Input className="self-input" placeholder="请输入" />
                        )}
                    </Form.Item>
                </div>
                <div className="flex">
                    <Form.Item label="计划状态" colon={false}>
                        {getFieldDecorator('status', {
                            initialValue: '',
                            rules: [{ required: false, message: '请选计划状态类型' }],
                        })(
                            <Select
                                placeholder="Select province"
                                className="self-select"
                                placeholder="请选择"
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                            >
                                <Option value=''>全部</Option>
                                {
                                    planOptions && planOptions.planStatusList && planOptions.planStatusList.map((item) => {
                                        return (<Option value={item.code} key={item.code}>{item.desc}</Option>)
                                    })
                                }
                            </Select>
                        )}
                    </Form.Item>

                    <Form.Item label="最近执行时间" colon={false}>
                        {getFieldDecorator('startTime', {
                            rules: [{ required: false }],
                        })(
                            <DatePicker
                                className="self-date"
                                showToday={false}
                                placeholder="选择开始时间"
                                onChange={selectStartTime}
                                disabledDate={disabledStartDate}
                                allowClear={false}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="">
                        {getFieldDecorator('endTime', {
                            rules: [{ required: false }],
                        })(
                            <DatePicker
                                className="self-date"
                                showToday={false}
                                placeholder="选择结束时间"
                                disabledDate={disabledEndDate}
                                onChange={selectEndTime}
                                allowClear={false}
                            />
                        )}
                    </Form.Item>
                    <Button className="blue-button btn_styls" htmlType="submit">查询</Button>
                    <Button className="white-button" onClick={onReset}>重置</Button>
                </div>
            </Form>
        </div>
    )
}

export default connect(({ deviceCheck }) => ({
    deviceCheck
}))(HeaderSearch)
